<template>
  <a-card :bordered="false" class="card-area" :loading="loading">
    <div v-show="!!formData.formKey">
      <iframe  :id="iframeId" :srcdoc="srcDoc"
               @load="handleIframeInitValue(formData)"
               frameborder="0"
               :style="`width: 100%;`" scrolling="auto"/>
    </div>
    <div v-show="!formData.formKey">
      <a-form :form="form">

        <a-form-item v-for="item in formData.formProperties" :key="item.id" v-if="item.readable"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="item.name">
          <a-input v-if="item.type=='string'"
                   :disabled="!item.writable"
                   v-decorator="[item.id, {rules:getValidator(item.required)}]"/>

          <a-input-number v-if="item.type=='double'"
                          :step="0.0001"
                   :disabled="!item.writable"
                   v-decorator="[item.id, {rules:getValidator(item.required)}]"/>
          <a-switch v-if="item.type=='boolean'"
                    :step="0.0001"
                    :disabled="!item.writable"
                    v-decorator="[item.id, {rules:getValidator(item.required)}]"/>
          <a-select v-if="item.type=='enum'"
                    :allowClear="true"
                   :disabled="!item.writable"
                   v-decorator="[item.id, {rules:getValidator(item.required)}]">
            <a-select-option v-for="data in item.enmuDatas" :value="data.value" :key="data.value">{{data.name}}</a-select-option>
          </a-select>
          <a-date-picker v-if="item.type=='data'"
                         :allowClear="true"
                         :disabled="!item.writable"
                         :valueFormat="(()=>item.datePattern.replace('Y', 'y'))()"
                         v-decorator="[item.id, {rules:(item.required?getValidatorRolesRequired():[])}]"/>

        </a-form-item>

      </a-form>
    </div>
    <div>
      <a-button v-if="buttonShow" @click="handleOk" type="primary">提交</a-button>
    </div>
  </a-card>
</template>

<script>
    import { randomUUID } from '../../../utils/util'
    import { activitiFormUrl, activitiProcessDefinitionUrl,activitiTaskUrl } from '../../../api/url'
    import { httpAction, postAction } from '../../../api/manage';
    import AkfhModelDrawMixin from '../../../mixin/AkfhModelDrawMixin';
    import pick from 'lodash.pick'

    export default {
        name: 'FormIframe',
        props:{
          buttonShow:{
            type:Boolean,
            required:false,
            default:true
          },
          propFormData:{
            type:Object,
            required: false,
            default:undefined
          }
        },
        beforeCreate() {
          this.form = this.$form.createForm(this);
        },
      mounted(){
          if(this.propFormData){
            this.loadData(this.propFormData)
          }
      },
      watch:{
        propFormData(v){
          if(v){
            this.loadData(v)
          }
        }
      },
      mixins:[AkfhModelDrawMixin],
        data(){
          return {
            loading:false,
            iframeId:randomUUID(),
            srcDoc:'',
            screenHeight:window.screen.availHeight,
            formData:{
              deploymentId:'',
              taskId:'',
              formKey:'',
              formProperties:[],
            },
            labelCol: {
              xs: { span: 24 },
              sm: { span: 5 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 16 },
            },
          }
        },
        methods:{
          loadData(formData){
            this.formData = formData;
            if(formData.formKey){
              httpAction({
                url:activitiProcessDefinitionUrl.resource,
                method:'get',
                responseType:'text',
                params:{ name:formData.formKey,deploymentId:formData.deploymentId }
              })
                .then(res=>{
                  this.srcDoc = res+'<div style="display: none"> '+new Date().getTime()+'</div>';
                  this.$nextTick(()=>{
                    let iframe = document.getElementById(this.iframeId);
                    try{
                      let bHeight = iframe.contentWindow.document.body.scrollHeight;
                      let dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
                      let height = Math.max(bHeight, dHeight);
                      iframe.height = height;
                    }catch (ex){}

                  })
                })
            }else {
              this.$nextTick(()=>{
                  this.handleFormInitValue(formData);

              })
            }


          },

          getFormData(){
            return new Promise((resolve, reject)=>{
              if(this.formData.formKey){
                let  data = this.handleIframeOk();
                resolve(data);
              }else {
                let data = this.handleFormOk();
                data.then((result) => {
                   resolve(result)
                }, (err)=>reject(err));
              }
            } );
          },
          handleOk(){

            if(this.formData.formKey){
              let  data = this.handleIframeOk();
              this.handleSendData(data);
            }else {
              let data = this.handleFormOk();
              data.then((result)=>{
                this.handleSendData(result);
              });
            }
          },
          handleSendData(data){
            this.loading = true;
            let url = "";
            if(this.formData.taskId){
              url = activitiTaskUrl.complate+"/"+this.formData.taskId;
            }else {
              url = activitiFormUrl.startProcess+"/"+this.formData.deploymentId;
            }
            postAction(url, data)
              .then(res=>{
                if(res.success){
                  this.$message.success(res.message);
                  this.$emit('ok');
                }
              }).finally(()=>{
              this.loading = false;
            })
          },
          handleFormOk(){
             return this.form.validateFields();
          },
          handleFormInitValue(formData){
            this.form.resetFields();
            let model = {};
            formData.formProperties.forEach(value => {
              model[value.id] = value.value;
            })
            this.$nextTick(() => {
              let names = [];
              for(let k in this.form.getFieldsValue()){
                names.push(k);
              }
              this.form.setFieldsValue(pick(model, names));
            });
          },
          handleIframeInitValue(formData){

         
            if(!document.getElementById(this.iframeId) || document.getElementById(this.iframeId).style.display == 'none' || 
            document.getElementById(this.iframeId).contentWindow.document.body.innerHTML == ''){
              setTimeout(()=>{this.handleIframeInitValue(formData)}, 200);
              return;
            }
            let ele = document.getElementById(this.iframeId);
            let win = ele.contentWindow;
            let doc = win.document;
            for (let j = 0; j < formData.formProperties.length; j++) {
              let value = formData.formProperties[j].value;
              let id = formData.formProperties[j].id;
              let inputs = doc.getElementsByTagName("input");
              for (let i = 0; i < inputs.length; i++) {

                let ip = inputs[i];
                if(ip.name != id) {
                  continue;
                }
                if(ip.type=='text' || ip.type=="hidden"
                  || ip.type=='password' || ip.type=="email"
                  ||ip.type=='url' || ip.type=="number"
                  ||ip.type=='range' || ip.type=="date"
                  ||ip.type=='month' || ip.type=="week"
                  ||ip.type=='time' || ip.type=="datetime"
                  ||ip.type=='datetime-local' || ip.type=="search"){
                  ip.value = value;
                };
                if(ip.type=="radio" && ip.value == value){
                   ip.checked = 'checked';
                }
                if(ip.type=="checkbox" && ip.value == value){
                 ip.checked = 'checked';
                }
              }
              let textareas = doc.getElementsByTagName("textarea");
              for (let i = 0; i < textareas.length; i++) {

                let t = textareas[i];
                if(t.name != id) {
                  continue;
                }
                t.innerHTML = value;
              }
              let selects = doc.getElementsByTagName("select");
              for (let i = 0; i < selects.length; i++) {
                let t = selects[i];
                if(t.name != id) {
                  continue;
                }
                let options = t.options;
                for (let k = 0; k < options.length; k++) {
                  if(value == options[k].value ) {
                    t.selectedIndex = k;
                    break;
                  }
                }
              }
            }

          },
          handleIframeOk(){
            let win = document.getElementById(this.iframeId).contentWindow;
            let doc = win.document;

            let data = {};
            let inputs = doc.getElementsByTagName("input");
            for (let i = 0; i < inputs.length; i++) {
              let ip = inputs[i];
              if(ip.type=='text' || ip.type=="hidden"
                || ip.type=='password' || ip.type=="email"
                ||ip.type=='url' || ip.type=="number"
                ||ip.type=='range' || ip.type=="date"
                ||ip.type=='month' || ip.type=="week"
                ||ip.type=='time' || ip.type=="datetime"
                ||ip.type=='datetime-local' || ip.type=="search"){
                data[ip.name] = ip.value;
              };
              if(ip.type=="radio" && ip.checked){
                data[ip.name] = ip.value;
              }
              if(ip.type=="checkbox" && ip.checked){
                if(!data[ip.name]){
                  data[ip.name]=[];
                }
                data[ip.name].push(ip.value);
              }
            }

            let textareas = doc.getElementsByTagName("textarea");
            for (let i = 0; i < textareas.length; i++) {
              let t = textareas[i];
              data[t.name]=t.innerHTML;
            }
            let selects = doc.getElementsByTagName("select");
            for (let i = 0; i < selects.length; i++) {
              let t = selects[i];
              data[t.name]=t.options[t.selectedIndex].value;
            }
            return data;
          }
        }
    }
</script>

<style scoped>

</style>